package cwinsor.raking.year2014;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import misc.ActionDemo;



/**
 * This class is the top-level leaf raking application
 * Main is provided below
 * 
 * @author cwinsor
 *
 */
public class LeafRakingJPanel extends JPanel implements ItemListener {

	private static final long serialVersionUID = 1L;
	protected String newline = "\n";
	protected Action fileOpenAction;
	protected Action fileSaveAction;
	protected Action fileCloseAction;
	protected Action scheduleGetNewPreferencesAction;


	JScrollPane scrollPaneCenter;
	JScrollPane scrollPaneEnd; 
	JTextArea bottomTextArea;

	JFileChooser fc;

	RakerAbstractTableModel abstractTbl;

	public LeafRakingJPanel() {
		super(new BorderLayout());


		fileOpenAction = new FileOpenAction(  "Open",
				createNavigationIcon("Back24"),
				"Open a raker file.", 
				new Integer(KeyEvent.VK_O));

		fileSaveAction = new FileSaveAction(  "Save",
				createNavigationIcon("Back24"),
				"Save the raker file", 
				new Integer(KeyEvent.VK_S));

		fileCloseAction = new FileCloseAction(  "Close (no save)",
				createNavigationIcon("Back24"),
				"Close the raker file", 
				new Integer(KeyEvent.VK_C));

		scheduleGetNewPreferencesAction = new ScheduleGetNewPreferencesAction(  "Get new preferences (from file)",
				createNavigationIcon("Back24"),
				"Get rakers' new schedule preferences from file", 
				new Integer(KeyEvent.VK_G));


		//Create a file chooser
		fc = new JFileChooser();
	}




	/*
	 * create menu bar
	 */
	private JMenuBar createMenuBar() {

		// create menu bar
		JMenuBar menuBar;
		JMenu menu;
		JMenuItem menuItem;

		menuBar = new JMenuBar();

		//file menu
		menu = new JMenu("File");
		menu.setMnemonic(KeyEvent.VK_F);
		menu.getAccessibleContext().setAccessibleDescription("file");

		menuItem = new JMenuItem(fileOpenAction);
		menuItem.setIcon(null); //arbitrarily chose not to use icon
		menu.add(menuItem);

		menuItem = new JMenuItem(fileSaveAction);
		menuItem.setIcon(null); //arbitrarily chose not to use icon
		menu.add(menuItem);

		menuItem = new JMenuItem(fileCloseAction);
		menuItem.setIcon(null); //arbitrarily chose not to use icon
		menu.add(menuItem);

		menuBar.add(menu);

		//schedule menu
		menu = new JMenu("Schedule");
		menu.setMnemonic(KeyEvent.VK_S);
		menu.getAccessibleContext().setAccessibleDescription("schedule");

		menuItem = new JMenuItem(scheduleGetNewPreferencesAction);
		menuItem.setIcon(null); //arbitrarily chose not to use icon
		menu.add(menuItem);

		menuBar.add(menu);

		return  menuBar;
	}




	/*
	 * create content pane
	 */
	private Container createContentPane() {

		setPreferredSize(new Dimension(700, 150));

		clearContentPane();
		//		JTextArea textArea;
		//		textArea = new JTextArea(500, 150);
		//		textArea.setText("(no file opened)");
		//		scrollPaneCenter = new JScrollPane(textArea);
		//		this.add(scrollPaneCenter, BorderLayout.CENTER);


		//Create a scrolled text area.
		bottomTextArea = new JTextArea(5, 150);
		bottomTextArea.setEditable(false);
		scrollPaneEnd= new JScrollPane(bottomTextArea);
		this.add(scrollPaneEnd, BorderLayout.PAGE_END);

		return this;	
	}


	/*
	 * fill content pane
	 */
	private void fillContentPane(File file) {

		abstractTbl = new RakerAbstractTableModel();
		abstractTbl.readDataFromFile(file);

		final JTable table = new JTable(abstractTbl);
		table.setPreferredScrollableViewportSize(new Dimension(50, 70));
		table.setAutoCreateRowSorter(true);
		table.setColumnSelectionAllowed(true);
		table.setFocusable(true);
		table.setFillsViewportHeight(true);

		//Create a scroll pane and add the table to it.
		this.remove(scrollPaneCenter);
		scrollPaneCenter = new JScrollPane(table);
		this.add(scrollPaneCenter, BorderLayout.CENTER);

		// revalidate and repaint
		this.validate();
		this.repaint();
	}

	/*
	 * update rakers' schedule preferences
	 */
	private void updateSchedulePreferences(File file) {
		abstractTbl.updateSchedulePreferencesFromFile(file);

		// revalidate and repaint
		this.validate();
		this.repaint();
	}


	/*
	 * save content pane
	 */
	private void saveContentPane(File file) {
		abstractTbl.writeDataToFile(file);
	}

	/*
	 * clear content pane
	 */
	private void clearContentPane() {
		//	this.remove(scrollPaneCenter);

		JTextArea textArea = new JTextArea(5, 30);
		textArea.setText("(no file opened)");
		scrollPaneCenter = new JScrollPane(textArea);
		this.add(scrollPaneCenter, BorderLayout.CENTER);

		// revalidate and repaint
		this.validate();
		this.repaint();
	}



	public class FileOpenAction extends AbstractAction {
		private static final long serialVersionUID = 1L;
		public FileOpenAction(String text, ImageIcon icon,
				String desc, Integer mnemonic) {
			super(text, icon);
			putValue(SHORT_DESCRIPTION, desc);
			putValue(MNEMONIC_KEY, mnemonic);
		}
		public void actionPerformed(ActionEvent e) {
			int returnVal = fc.showOpenDialog(LeafRakingJPanel.this);
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				File file = fc.getSelectedFile();
				//////////////////////
				// open the file, read it in and populate the content pane
				displayResult("Opening: " + file.getName() + "  (" + file.getPath() + ")");
				fillContentPane(file);
			} else {
				displayResult("Open command cancelled by user.");
			}
		}
	}

	public class FileSaveAction extends AbstractAction {
		private static final long serialVersionUID = 1L;
		public FileSaveAction(String text, ImageIcon icon,
				String desc, Integer mnemonic) {
			super(text, icon);
			putValue(SHORT_DESCRIPTION, desc);
			putValue(MNEMONIC_KEY, mnemonic);
		}
		public void actionPerformed(ActionEvent e) {
			int returnVal = fc.showSaveDialog(LeafRakingJPanel.this);
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				File file = fc.getSelectedFile();
				//////////////////////
				// write the file out to disk
				displayResult("Saving: " + file.getName() + "  (" + file.getPath() + ")");
				saveContentPane(file);
			} else {
				displayResult("Save command cancelled by user." + newline);
			}
		}
	}

	public class FileCloseAction extends AbstractAction {
		private static final long serialVersionUID = 1L;
		public FileCloseAction(String text, ImageIcon icon,
				String desc, Integer mnemonic) {
			super(text, icon);
			putValue(SHORT_DESCRIPTION, desc);
			putValue(MNEMONIC_KEY, mnemonic);
		}
		public void actionPerformed(ActionEvent e) {
			displayResult("Closing file");
			clearContentPane();
		}
	}

	public class ScheduleGetNewPreferencesAction extends AbstractAction {
		private static final long serialVersionUID = 1L;
		public ScheduleGetNewPreferencesAction(String text, ImageIcon icon,
				String desc, Integer mnemonic) {
			super(text, icon);
			putValue(SHORT_DESCRIPTION, desc);
			putValue(MNEMONIC_KEY, mnemonic);
		}
		public void actionPerformed(ActionEvent e) {
			int returnVal = fc.showOpenDialog(LeafRakingJPanel.this);
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				File file = fc.getSelectedFile();
				//////////////////////
				// open the file, read it in and populate the content pane
				displayResult("Opening: " + file.getName() + "  (" + file.getPath() + ")");
				updateSchedulePreferences(file);
			} else {
				displayResult("GetNewPreferences command cancelled by user.");
			}
		}
	}

	public void itemStateChanged(ItemEvent e) {
		JCheckBoxMenuItem mi = (JCheckBoxMenuItem)(e.getSource());
		boolean selected =
				(e.getStateChange() == ItemEvent.SELECTED);

		//Set the enabled state of the appropriate Action.
		if (mi == fileOpenAction) {
			fileOpenAction.setEnabled(selected);
		}
	}

	/** Returns an ImageIcon, or null if the path was invalid. */
	protected static ImageIcon createNavigationIcon(String imageName) {
		String imgLocation = "toolbarButtonGraphics/navigation/"
				+ imageName
				+ ".gif";
		java.net.URL imageURL = ActionDemo.class.getResource(imgLocation);

		if (imageURL == null) {
			System.err.println("Resource not found: "
					+ imgLocation);
			return null;
		} else {
			return new ImageIcon(imageURL);
		}
	}


	public void displayResult(String message) {
		String s = (message
				+ newline);
		bottomTextArea.append(s);
	}

	/*
	 * static method
	 * construct (static) frame
	 * adds stuff to that
	 * including a content panel (instance of this class) raker table
	 */
	private static void createAndShowGUI(){

		//Create and set up the frame
		JFrame frame = new JFrame("BHRA Leaf Raking");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		LeafRakingJPanel leafRakingJPanel = new LeafRakingJPanel();
		frame.setJMenuBar(leafRakingJPanel.createMenuBar());
		frame.setContentPane(leafRakingJPanel.createContentPane());

		//Display the window.
		frame.setSize(450, 260);
		frame.setVisible(true);
	}

	/*
	 * main entry point - thread safe
	 */
	public static void main(String[] args){
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});
	}



	/**
	 * debug message
	 */
	String dM = this.getClass().getSimpleName();


}